package com.ece.devirtualizus.Services;

import java.util.Date;
import java.util.List;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.ece.devirtualizus.Dao.ContinuousReleveDao;
import com.ece.devirtualizus.Dao.SqlLiteGpsPositionDao;
import com.ece.devirtualizus.Dao.SqlLiteUserDao;
import com.ece.devirtualizus.ModelDto.GpsPositionDto;

public class GpsService extends Service implements LocationListener {
	private LocationManager locationManager = null;
	// String provider="";
	// Location location=null;
	String userID = "";
	private SqlLiteGpsPositionDao gpsDao;

	// boolean isFirstLocation;

	public GpsService() {
		// TODO Auto-generated constructor stub

	}

	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		return netInfo != null && netInfo.isConnectedOrConnecting();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		Log.i("onStartCommand GPS SERVICE -- debut", "");
		String provider = "";
		Location location = null;
		this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		provider = getProvider();

		this.locationManager.requestLocationUpdates(provider, 60000, 0, this);
		location = getLastLocation(provider);
		
		recordGpsPositionInSqlLite(location);

		// GET USER ID
		SqlLiteUserDao userDao = new SqlLiteUserDao(this);
		userDao.open();
		userID = userDao.getUserId();
		if (userID.equals("")) {
			Log.e("onStartCommand.getUserIfFromSqlLITE", "NO USER");
		}
		Log.i("GpsService.onStartCommand",userID);

		if (isOnline() && !userID.equals("")) {
			Log.i("onStartCommand.isOnline", "NETWORK OK");
			List<GpsPositionDto> values = this.gpsDao.getAllCacheGpsPosition();
			Log.i("gpsDao.getAllCacheGpsPosition",
					"values.size():" + values.size());
			ContinuousReleveDao dao = new ContinuousReleveDao();
			// this.userID=intent.getExtras().getString("userID");
			dao.storeListGpsPosition(this.userID, values);
			Log.d("GPS POSTION USER ID", userID);
		} else {
			Log.e("onStartCommand.isOnline", "NO NETWORK");
		}

		Log.i("onStartCommand -- fin", "");

		return Service.START_STICKY;
	}

	private String getProvider() {
		Criteria criteria = new Criteria();
		String provider = locationManager.getBestProvider(criteria, false);
		return provider;
	}

	private Location getLastLocation(String receivedProvider) {
		Location location = null;
		try {
			location = locationManager.getLastKnownLocation(receivedProvider);
			Log.i("getCurrentLocation", "Location:" + location.toString());
			return location;

		} catch (Exception e) {
			Log.e("getCurrentLocation", "Location:" + "LOCATION INTROUVABLE");
			Location locationParis = new Location(receivedProvider);
			locationParis.setLatitude(48.85197128);
			locationParis.setLongitude(2.28592275);
			location = locationParis;
			return location;
		}

	}

	private void recordGpsPositionInSqlLite(Location newLocation) {
		Date date = new Date();
		GpsPositionDto gpsPosition = new GpsPositionDto(newLocation, date);
		try {
			this.gpsDao = new SqlLiteGpsPositionDao(this);
			this.gpsDao.open();
			this.gpsDao.createGpsPosition(gpsPosition);
			Log.i("GpsService.recordGpsPosition--fin", "OK");

		} catch (Exception e) {
			Log.e("GpsService.recordGpsPositionInSqlLite", e.getMessage());
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		Log.i("OnLocationChange", "" + location.getLatitude());
		if (isOnline()) {
			Log.i("onStartCommand.onLocationChanged.isOnline", "OK");
			List<GpsPositionDto> values = this.gpsDao.getAllCacheGpsPosition();
			Log.i("gpsDao.onLocationChanged.getAllCacheGpsPosition",
					"values.size():" + values.size());
			ContinuousReleveDao dao = new ContinuousReleveDao();
			// this.userID=intent.getExtras().getString("userID");
			dao.storeListGpsPosition(this.userID, values);
		} else {
			Log.i("onStartCommand.onLocationChanged.isOnline", "NOK");
			recordGpsPositionInSqlLite(location);

		}
		locationManager.removeUpdates(this);
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

}
